﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Core;
using Tesla.Graphics;
using Tesla.Graphics.Implementation;
using Tesla.Xna.Util;
using XFG = Microsoft.Xna.Framework.Graphics;


namespace Tesla.Xna.Graphics.Implementation {
    /// <summary>
    /// Concrete XNA 4.0 implementation of a <see cref="VertexBuffer"/>.
    /// </summary>
    public sealed class XNAVertexBufferImplementation : VertexBufferImplementation {
        private XNARenderer _renderer;
        private XFG.GraphicsDevice _graphicsDevice;
        private XFG.VertexBuffer _vertexBuffer;

        /// <summary>
        /// Gets the XNA renderer that created this object.
        /// </summary>
        internal XNARenderer Renderer {
            get {
                return _renderer;
            }
        }

        /// <summary>
        /// Gets the actual XNA VertexBuffer object.
        /// </summary>
        internal XFG.VertexBuffer XNAVertexBuffer {
            get {
                return _vertexBuffer;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="XNAVertexBufferImplementation"/>.
        /// </summary>
        /// <param name="renderer">The XNA renderer.</param>
        /// <param name="decl">The vertex declaration.</param>
        /// <param name="vertexCount">The vertex count.</param>
        /// <param name="usage">The resource usage.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error creating the XNA buffer</exception>
        internal XNAVertexBufferImplementation(XNARenderer renderer, VertexDeclaration decl, int vertexCount, ResourceUsage usage)
            : base(decl, vertexCount, usage) {

                _renderer = renderer;
                _graphicsDevice = renderer.GraphicsDevice;

                try {
                    XFG.VertexDeclaration xnaDecl = XNAHelper.ToXNAVertexDeclaration(decl);
                    if(usage == ResourceUsage.Static) {
                        _vertexBuffer = new XFG.VertexBuffer(_graphicsDevice, xnaDecl, vertexCount, XFG.BufferUsage.None);
                    } else {
                        _vertexBuffer = new XFG.DynamicVertexBuffer(_graphicsDevice, xnaDecl, vertexCount, XFG.BufferUsage.None);
                    }
                } catch(Exception e) {
                    Dispose();
                    throw new TeslaException("Error creating XNA buffer: \n" + e.Message, e);
                }
        }

        /// <summary>
        /// Creates a new instance of <see cref="XNAVertexBufferImplementation"/> initialized with the interleaved data.
        /// </summary>
        /// <param name="renderer">The XNA renderer.</param>
        /// <param name="decl">The vertex declaration.</param>
        /// <param name="usage">The resource usage.</param>
        /// <param name="data">The interleaved data.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error creating or writing to the XNA buffer</exception>
        internal XNAVertexBufferImplementation(XNARenderer renderer, VertexDeclaration decl, ResourceUsage usage, DataBuffer data)
            : base(decl, usage, data) {

                _renderer = renderer;
                _graphicsDevice = renderer.GraphicsDevice;
                try {
                    XFG.VertexDeclaration xnaDecl = XNAHelper.ToXNAVertexDeclaration(decl);
                    if(usage == ResourceUsage.Static) {
                        _vertexBuffer = new XFG.VertexBuffer(_graphicsDevice, xnaDecl, base.VertexCount, XFG.BufferUsage.None);
                    } else {
                        _vertexBuffer = new XFG.DynamicVertexBuffer(_graphicsDevice, xnaDecl, base.VertexCount, XFG.BufferUsage.None);
                    }

                    _vertexBuffer.SetData<byte>(data.ByteDataCopy);
                } catch(Exception e) {
                    Dispose();
                    throw new TeslaException("Error creating XNA buffer: \n" + e.Message, e);
                }
        }

        /// <summary>
        /// Creates a new instance of <see cref="XNAVertexBufferImplementation"/> initialized with the vertex data array.
        /// </summary>
        /// <param name="renderer">The XNA renderer.</param>
        /// <param name="decl">The vertex declaration.</param>
        /// <param name="usage">The resource usage.</param>
        /// <param name="data">The array of vertex data.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error creating or writing to the XNA buffer</exception>
        internal XNAVertexBufferImplementation(XNARenderer renderer, VertexDeclaration decl, ResourceUsage usage, params DataBuffer[] data) 
            : base(decl, usage, data) {

                _renderer = renderer;
                _graphicsDevice = renderer.GraphicsDevice;
                try {
                    XFG.VertexDeclaration xnaDecl = XNAHelper.ToXNAVertexDeclaration(decl);
                    if(usage == ResourceUsage.Static) {
                        _vertexBuffer = new XFG.VertexBuffer(_graphicsDevice, xnaDecl, base.VertexCount, XFG.BufferUsage.None);
                    } else {
                        _vertexBuffer = new XFG.DynamicVertexBuffer(_graphicsDevice, xnaDecl, base.VertexCount, XFG.BufferUsage.None);
                    }

                    SetInterleavedData(data);
                } catch(Exception e) {
                    Dispose();
                    throw new TeslaException("Error creating XNA buffer: \n" + e.Message, e);
                }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="XNAVertexBufferImplementation"/> is reclaimed by garbage collection.
        /// </summary>
        ~XNAVertexBufferImplementation() {
            Dispose(false);
        }

        /// <summary>
        /// Convienence method that takes an array of data buffers, each representing a vertex element (in the order
        /// declared by the vertex declaration), and writes all of the data to the vertex buffer. The buffers must match
        /// the vertex declaration as well as the byte sizes of each element and all be of the same length.
        /// </summary>
        /// <param name="data">Array of databuffers representing the vertex data.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the number of buffers do not match the number
        /// of vertex elements, or if the number of vertices in each buffer does not match the vertex count,
        /// or if there is a byte size mismatch of any kind.</exception>
        public override void SetInterleavedData(params DataBuffer[] data) {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("data", "Data cannot be null.");
            }

            VertexDeclaration vertexDecl = base.VertexDeclaration;
            int vertexCount = base.VertexCount;

            //Verify if the incoming vertex streams match right with the supplied vertex declaration
            VertexElement[] elems = vertexDecl.VertexElements;
            if(elems.Length != data.Length) {
                throw new ArgumentOutOfRangeException("data", "Number of vertex streams do not match up the number of declared vertex elements.");
            }

            int totalSizeInBytes = 0;
            int vertexStride = 0;

            for(int i = 0; i < data.Length; i++) {
                DataBuffer db = data[i];
                VertexElement element = elems[i];
                int vSizeInBytes = db.ElementSizeInBytes;
                int vCount = db.SizeInBytes / vSizeInBytes;

                if(vCount != vertexCount) {
                    throw new ArgumentOutOfRangeException("data", "Vertex count mismatch, buffers must be of same length.");
                }
                if(vSizeInBytes != VertexDeclaration.GetVertexElementSize(element.Format)) {
                    throw new ArgumentOutOfRangeException("data", "Supplied vertex buffer element size mismatch with actual vertex element size.");
                }

                totalSizeInBytes += db.SizeInBytes;
                vertexStride += vSizeInBytes;
                db.Position = 0;
            }

            if(totalSizeInBytes != vertexDecl.VertexStride * vertexCount) {
                throw new ArgumentOutOfRangeException("data", "Vertex data must match the size of the vertex buffer in bytes!");
            }

            DataBuffer<byte> interleaved = new DataBuffer<byte>(vertexCount * vertexDecl.VertexStride);
            byte[] vertex = new byte[vertexStride];
            for(int i = 0; i < vertexCount; i++) {
                int startIndex = 0;
                for(int j = 0; j < data.Length; j++) {
                    DataBuffer db = data[j];
                    int elementSize = db.ElementSizeInBytes;
                    db.Get(vertex, startIndex, elementSize);
                    startIndex += elementSize;
                }
                interleaved.Set(vertex, 0, vertexStride);
            }
            _vertexBuffer.SetData<byte>(interleaved.Buffer);
            
        }

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes.</param>
        /// <param name="writeOptions">Writing options for the vertex buffer. None, discard, or no overwrite.</param>
        public override void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride, DataWriteOptions writeOptions) {
            if(base.BufferUsage == ResourceUsage.Static) {
                _vertexBuffer.SetData<T>(offsetInBytes, data, startIndex, elementCount, vertexStride);
            } else {
                if(writeOptions == DataWriteOptions.None) {
                    ((XFG.DynamicVertexBuffer) _vertexBuffer).SetData<T>(offsetInBytes, data, startIndex, elementCount, vertexStride, XFG.SetDataOptions.None);
                } else {
                    XFG.SetDataOptions mode = (writeOptions == DataWriteOptions.Discard) ? XFG.SetDataOptions.Discard : XFG.SetDataOptions.NoOverwrite;
                    ((XFG.DynamicVertexBuffer) _vertexBuffer).SetData<T>(offsetInBytes, data, startIndex, elementCount, vertexStride, mode);
                }
            }
        }

        /// <summary>
        /// Gets the data from the vertex buffer and copies it into specified array.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array to copy contents to from the vertex buffer into</param>
        /// <param name="startIndex">Index of the element in the array at each to start writing to</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes</param>
        public override void GetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride) {
            _vertexBuffer.GetData<T>(offsetInBytes, data, startIndex, elementCount, vertexStride);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing) {
            if(!IsDisposed) {
                //Dispose of managed resources
                if(disposing) {
                    if(_vertexBuffer != null) {
                        _vertexBuffer.Dispose();
                    }
                }
            }
            base.Dispose(disposing);
        }
    }
}
